package pri.hillchen.springbootstd.bms.shiro.util;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import pri.hillchen.springbootstd.bms.common.util.IdWorker;
import pri.hillchen.springbootstd.bms.shiro.ShiroUser;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by hillchen on 2017/10/18 0018.
 */
public class ShiroUtil {
    private static final String SESSION_TOKEN="sessionToken";
    /**
     * 获取已登录的用户信息
     * @return
     */
    public static ShiroUser getUser(){
        Subject subject = SecurityUtils.getSubject();
        if(subject != null){
            PrincipalCollection principals = subject.getPreviousPrincipals();
            if(principals != null){
                Object primaryPrincipal = principals.getPrimaryPrincipal();
                if(primaryPrincipal != null){
                    return (ShiroUser) primaryPrincipal;
                }
            }
        }
        return null;
    }
    public static HttpServletRequest getCurrentRequest(){
        ServletRequestAttributes ra = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        return ra.getRequest();
    }
    public static HttpSession getCurrentSession(){
        return getCurrentRequest().getSession();
    }
    public static String getSessionToken(){
        Object sessionToken = getCurrentSession().getAttribute(SESSION_TOKEN);
        return sessionToken == null ? null : sessionToken.toString();
    }
    public static void createSessionToken(){
        getCurrentSession().setAttribute(SESSION_TOKEN, IdWorker.getInstance().nextId());
    }
    public static void removeSessionToken(){
        getCurrentSession().removeAttribute(SESSION_TOKEN);
    }
}
